package org.Lin.server;

import org.Lin.util.AESUtil;
import org.json.JSONObject;

import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class NetworkServer {

    private static final int PORT = 5545;

    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(PORT);
        System.out.println("服务器启动在端口 " + PORT);

        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(() -> handleClient(socket)).start();
        }
    }

    private static void handleClient(Socket socket) {
        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
            String encryptedData = in.readLine();
            String decryptedData = AESUtil.decrypt(encryptedData);

            // 存储原始数据
            String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            Files.write(Paths.get("logs/" + timestamp + ".json"), decryptedData.getBytes());

            // 解析并分发
            JSONObject json = new JSONObject(decryptedData);
            String type = json.getString("type");

            switch (type) {
                case "login": LoginServer.handle(json); break;
                case "register": RegisterServer.handle(json); break;
                case "chatroom_message": ChatRoomServer.handle(json); break;
                case "friend_message": FriendMessageServer.handle(json); break;
                case "admin_operation": AdminServer.handle(json); break;
                default:
                    System.out.println("未知请求类型");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void send(String message) {
        // 可选：用于广播或多客户端通信
    }
}
